package com.ywy.common.exception;

import cn.hutool.json.JSONUtil;
import com.ywy.common.rest.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理
 *
 * @author ywy
 * @date 2021/12/29 10:42
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 自定义异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomApiException.class)
    @ResponseBody
    public Result jsonErrorHandler(CustomApiException e) {
        return Result.failure(e.getMessage());
    }

    /**
     * 参数校验异常捕获
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handlerException(MethodArgumentNotValidException e, HttpServletResponse response) {
        BindingResult bindingResult = e.getBindingResult();
        // 解析异常信息
        String errorMessage = bindingResult.getFieldError().getDefaultMessage();
        return Result.failure(errorMessage);
    }

    /**
     * 默认异常处理
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws IOException {
        log.error("GlobalExceptionHandler----->捕捉到全局异常：", e);

        // Ajax请求异常处理
        String header = req.getHeader("X-Requested-With");
        if(header != null  && "XMLHttpRequest".equals(header)) {
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().print(JSONUtil.toJsonStr(Result.failure(e.getMessage())));
            return null;
        }

        // 特殊异常信息处理
        if (e instanceof NullPointerException) {
            //...
        }

        // Web请求异常处理
        ModelAndView mav = new ModelAndView("/error/500");
        mav.addObject("message", e.getMessage());
        return mav;
    }
}
